import { defineStore } from 'pinia'
import categoryApi, { type categoryModel } from '@/api/category'
import { ElMessage } from 'element-plus'

interface categoryStoreModel {
    category1Id: undefined | number,
    category2Id: undefined | number,
    category3Id: undefined | number,
    category1List: categoryModel[],
    category2List: categoryModel[],
    category3List: categoryModel[]
}
const resetCategoryStore = (): categoryStoreModel => ({
    category1Id: undefined,
    category2Id: undefined,
    category3Id: undefined,
    category1List: [],
    category2List: [],
    category3List: []
})

const useCategoryStore = defineStore('category', {
    state() {
        return {
            ...resetCategoryStore()
        }
    },
    actions: {
        async getCategory1() {
            try {
                let result = await categoryApi.getCategory1();
                this.category1List = result;
            } catch (error) {
                ElMessage.error('获取一级列表失败')
                return Promise.reject(error)
            }
        },
        async getCategory2(category1Id: number) {
            this.category2Id = undefined
            this.category2List = []
            this.category3Id = undefined
            this.category3List = []
            try {
                let result = await categoryApi.getCategory2(category1Id)
                this.category2List = result
            } catch (error) {
                ElMessage.error('获取二级列表失败')
                return Promise.reject(error)
            }
        },
        async getCategory3(category2Id: number) {
            this.category3Id = undefined
            this.category3List = []
            try {
                let result = await categoryApi.getCategory3(category2Id)
                this.category3List = result;
            } catch (error) {
                ElMessage.error('获取三级列表失败')
                return Promise.reject(error)
            }
        }
    },
    getters: {

    }
})

export default useCategoryStore